package com.example.springboot2.repository;

import com.example.springboot2.entity.Merchant;
import com.example.springboot2.entity.Order;
import com.example.springboot2.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 订单Repository
 */
@Repository
public interface OrderRepository extends JpaRepository<Order, Long>, JpaSpecificationExecutor<Order> {

    /**
     * 根据订单号查找订单
     */
    Optional<Order> findByOrderNo(String orderNo);

    /**
     * 根据商家查找订单
     */
    Page<Order> findByMerchant(Merchant merchant, Pageable pageable);

    /**
     * 根据商家和状态查找订单
     */
    Page<Order> findByMerchantAndStatus(Merchant merchant, Order.OrderStatus status, Pageable pageable);

    /**
     * 根据客户查找订单
     */
    Page<Order> findByCustomer(User customer, Pageable pageable);

    /**
     * 统计商家订单数量
     */
    long countByMerchant(Merchant merchant);

    /**
     * 统计商家指定状态订单数量
     */
    long countByMerchantAndStatus(Merchant merchant, Order.OrderStatus status);

    /**
     * 统计商家指定时间范围内的订单数量
     */
    @Query("SELECT COUNT(o) FROM Order o WHERE o.merchant = :merchant AND o.createdTime BETWEEN :startTime AND :endTime")
    long countByMerchantAndCreatedTimeBetween(@Param("merchant") Merchant merchant, 
                                              @Param("startTime") LocalDateTime startTime, 
                                              @Param("endTime") LocalDateTime endTime);

    /**
     * 统计商家指定时间范围内的销售额
     */
    @Query("SELECT COALESCE(SUM(o.actualAmount), 0) FROM Order o WHERE o.merchant = :merchant AND o.status IN ('PAID', 'SHIPPED', 'DELIVERED', 'FINISHED') AND o.createdTime BETWEEN :startTime AND :endTime")
    BigDecimal sumActualAmountByMerchantAndCreatedTimeBetween(@Param("merchant") Merchant merchant, 
                                                              @Param("startTime") LocalDateTime startTime, 
                                                              @Param("endTime") LocalDateTime endTime);

    /**
     * 查找商家今日订单
     */
    @Query("SELECT o FROM Order o WHERE o.merchant = :merchant AND DATE(o.createdTime) = DATE(CURRENT_TIMESTAMP)")
    List<Order> findTodayOrdersByMerchant(@Param("merchant") Merchant merchant);
}
